package Util;

import java.io.IOException;

import javax.persistence.EntityManager;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.catalina.realm.RealmBase;

import Entidade.Usuario;

/**
 * Servlet Filter implementation class UsuarioFilter2
 */
public class UsuarioFilter2 implements Filter {

	
	public static String entidade ="sistemaDarlan";
    /**
     * Default constructor. 
     */
    public UsuarioFilter2() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest req, ServletResponse response, FilterChain chain) throws IOException, ServletException {


		HttpServletRequest request = (HttpServletRequest) req;
		HttpSession session = ((HttpServletRequest) request).getSession();
		
		EntityManager manager = Persistence.createEntityManagerFactory(entidade).createEntityManager();
		
		 if (manager.createQuery("From Usuario").getResultList().size()==0){
			 Usuario m = new Usuario();
			 
			    m.setPerfil("admin");
		     	m.setLogin("Darlan");	
				m.setNome("Darlan");
				m.setSenha(RealmBase.Digest("Darlan", "MD5", "UTF-8"));
				
				manager.getTransaction().begin();
				
				manager.persist(m);
				
			    manager.getTransaction().commit();
			    manager.close();
		 }
		/*
		 * 
		 * 		if (em.createQuery("from Regiao").getResultList().size() == 0 &&
				em.createQuery("from Perfil").getResultList().size() == 0 &&
				em.createQuery("from Usuario").getResultList().size() == 0 &&
				em.createQuery("from Parametro").getResultList().size() == 0){
			atualizarSeguranca = true;
		}
		 * 
		 */
		
		
		
		
		/*if (session.getAttribute("UsuarioLogado") == null) {

			String loginUser = request.getRemoteUser();
			Usuario user = null;

			EntityManager manager = Persistence.createEntityManagerFactory(entidade).createEntityManager();

			//Query q = manager.createQuery("from Produto p");
			// sessao user
			Query use = manager.createQuery("from Usuario u where u.login = :login");
			use.setParameter("login", loginUser);

			user = (Usuario) use.getSingleResult();

			session.setAttribute("UsuarioLogado", user);

		}
		
		*/
		chain.doFilter(req,response);
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}
